package com.inphase.doc.service;

import com.inphase.doc.config.OfficeWeb365Properties;
import com.inphase.doc.config.WopiProperties;
import com.inphase.doc.utils.FillFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class WopiServiceImpl implements WopiService{

    @Autowired
    WopiProperties wopiProperties;
    @Autowired
    OfficeWeb365Properties officeWeb365Properties;


    public String clientUrl(String uuid) {
//        todo 根据资源加载资源信息
        String id = "123";
        String extName="doc";

        return buildUrl(id,extName);
    }

    /**
     * 构建资源预览界面
     * @param id  资源标志
     * @param extName 资源扩展名（doc(x)，ppt(x),pdf,wps）
     * @return
     */
    public String buildUrl(String id,String extName) {

        Map<String,String> params =new HashMap<>();
        params.put("scheme",wopiProperties.getServerScheme());
        params.put("domain",wopiProperties.getServerHost());

        // 实现文件下载请求路径
        params.put("uuid",id);
        //文件扩展名
        params.put("ext",extName.trim().toLowerCase());
        //nginx 代理标志
        params.put("nginxProxy",officeWeb365Properties.getNginxProxy());


        //设置资源下载位置
        String wopiUrl = "{{scheme}}://{{domain}}/wopi/files/{{nginxProxy}}/{{uuid}}.{{ext}}";
        wopiUrl = FillFormat.render(wopiUrl, params);
        try {
            wopiUrl = URLEncoder.encode(wopiUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            wopiUrl ="/error";
        }

        //设置office web 365下载路径
        params.clear();
        params.put("furl", wopiUrl);
        String url =  FillFormat.render(officeWeb365Properties.getHost(), params);

        return url;
    }
}
